<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/7/11
 * Time: 17:18
 */

namespace iBrand\Store\Backend\Service;

use iBrand\Component\Goods\Models\GoodsSpecRelation;
use iBrand\Component\Goods\Models\Season;
use iBrand\Component\Goods\Models\Style;

use iBrand\Store\Backend\Model\Brand;
use iBrand\Store\Backend\Model\Goods;
use iBrand\Store\Backend\Model\GoodsCategory;
use iBrand\Store\Backend\Model\Models;
use iBrand\Store\Backend\Model\Product;
use iBrand\Store\Backend\Model\SpecsValue;
use iBrand\Store\Backend\Model\Spec;
use iBrand\Store\Backend\Model\Category;
use Illuminate\Support\Collection;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use DB;
use iBrand\Shop\Backend\Repository\O2oGoodsProductsRepository;
use iBrand\Shop\Backend\Repository\O2oGoodsRepository;

class ImportGoodsService
{
    protected $log;
    protected $o2oGoodsRepository;
    protected $o2oGoodsProductsRepository;

    public function __construct(O2oGoodsRepository $o2oGoodsRepository,
                                O2oGoodsProductsRepository $o2oGoodsProductsRepository)
    {
        $this->log = new Logger('registration');
        $this->log->pushHandler(
            new StreamHandler(
                storage_path('logs/laravel-import_goods.log'),
                Logger::INFO
            )
        );

        $this->o2oGoodsRepository = $o2oGoodsRepository;
        $this->o2oGoodsProductsRepository = $o2oGoodsProductsRepository;
    }

    /**
     * 处理商品数据导入
     * @param $data
     */
    public function handleImportGoods($data, $import_shop)
    {

        foreach ($data as $item) {
            $_name = $item['name'];
            $_goods_no = $item['goods_no'];
            $_brand = $item['brand'];
            $_model = $item['model'];
            $_category = $item['category'];
            $_factory_price = $item['factory_price'];
            $_sell_price = $item['sell_price'];
            $_market_price = $item['market_price'];
            $_style = $item['style'];
            $_season = $item['season'];
            $_gender = $item['gender'];
            $_year = $item['year'];
            $_color = $item['color'];
            $_size = $item['size'];
            $_skus = $item['sku'];

            $brand = Brand::where('name', $_brand)->first();
            $goods = Goods::where('goods_no', $_goods_no)->first();
            $model = Models::where('name', $_model)->first();
            $style = Style::where('name', $_style)->first();
            $season = Season::where('name', $_season)->first();
            \Log::info($_skus);

            //如果没有设置品牌 OR 商品已经存在 OR 没有模型，中断
            if (!$brand) {

                $brand = Brand::create(['name' => $_brand]);
                /*$this->log->addInfo("goods_no：" . $_goods_no . ' 没有匹配到品牌');
                continue;*/
            }

            /*if ($goods) {
                $this->log->addInfo("goods_no：" . $_goods_no . ' 已经存在');
                continue;
            }*/

            if (!$model) {
                $this->log->addInfo("goods_no：" . $_goods_no . ' 匹配不到模型');
                continue;
            }

            if ($_gender == '通款') {
                $gender = 0;
            } elseif ($_gender == '女') {
                $gender = 2;
            } else {
                $gender = 1;
            }

            try {
                DB::beginTransaction();

                if (!$goods) {
                    //商品基础数据
                    $goods = Goods::create([
                        'name' => $_name,
                        'goods_no' => $_goods_no,
                        'brand_id' => $brand->id,
                        'model_id' => $model->id,
                        'supplier_id' => 1,
                        'style_id' => $style ? $style->id : 0,
                        'season_id' => $season ? $season->id : 0,
                        'year' => $_year,
                        'gender' => $gender,
                        'market_price' => $_market_price,
                        'factory_price' => $_factory_price,
                        'sell_price' => $_sell_price
                    ]);

                    $category = $this->importCategory($_category, $_goods_no);
                    $goods->categories()->sync($category);
                }

                $o2oGoodsId = 0;
                if ($import_shop) {
                    $o2oGoods = $this->o2oGoodsRepository->findWhere(['status' => 1, 'goods_id' => $goods->id, 'shop_id' => $import_shop])->first();
                    if (!$o2oGoods) {
                        $o2oGoods = $this->o2oGoodsRepository->create([
                            'goods_id' => $goods->id,
                            'shop_id' => $import_shop,
                            'price' => $_factory_price,
                        ]);
                    }
                    $o2oGoodsId = $o2oGoods->id;
                }


                $this->importProduct($_color, $_size, $_sell_price, $_market_price, $goods, $_brand, $_skus, $o2oGoodsId, $import_shop);

                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                \Log::info($exception->getTraceAsString());
                $this->log->addInfo("goods_no：" . $_goods_no . $exception->getMessage());
            }
        }
    }

    /**
     * 处理product和spec_relation数据
     * @param $data
     * @param $specIds
     * @param $e_skus : excel里面的sku编码
     * @return array|bool
     */
    private function importProduct($color, $size, $sell_price, $market_price, $goods, $brand, $e_skus, $o2oGoodsId, $shop_id)
    {
        $colors = explode(',', $color);
        $sizes = explode(',', $size);

        $colors = array_filter($colors);
        $sizes = array_filter($sizes);

        foreach ($colors as $key => $cl) {
            if (!$colorSpecsValue = SpecsValue::where('name', $cl)->first()) {
                SpecsValue::create(['spec_id' => 2, 'name' => $cl, 'rgb' => 'ffffff']);
            } else {
                /*if (GoodsSpecRelation::where('goods_id', $goods->id)->where('spec_value_id', $colorSpecsValue->id)->first()) {
                    unset($colors[$key]);
                }*/
            }
        }

        if (count($colors) == 0) {
            \Log::info('color return' . $e_skus);
            return;
        }

        foreach ($sizes as $sz) {
            if (!SpecsValue::where('name', $sz)->first()) {
                SpecsValue::create(['spec_id' => 1, 'name' => $sz]);
            }
        }

        //用于STARROOM数据导入
        if ($brand == 'STARROOM' OR env('OTHER_CUS')) {
            $skuData = $this->combineArraySr($colors, $sizes, $goods);
            $skus = $skuData[0];
            $skuCode = $skuData[1];
        } else {
            $skus = $this->combineArray($colors, $sizes);
        }

        foreach ($skus as $key => $sku) {
            $product = [
                'goods_id' => $goods->id,
                'sku' => $goods->goods_no . substr(time(), -6) . mt_rand(),
                'sell_price' => $sell_price,
                'market_price' => $market_price,
                'is_show' => 1,
                'specID' => implode('-', $sku)
            ];


            $product['sku'] = $skuCode[$key];
            if (env('OTHER_CUS') OR $brand == 'STARROOM') {
                $product['sku'] = $e_skus;
            }else{
                $product['sku'] = $skuCode[$key];
            }

            if (Product::where('sku', $product['sku'])->first()) {
                continue;
            }


            /*if (GoodsSpecRelation::where('goods_id', $goods->id)->where('spec_value_id', $sku[0])->first() AND
                GoodsSpecRelation::where('goods_id', $goods->id)->where('spec_value_id', $sku[1])->first()
            ) {
                continue;
            }*/


            $bproduct = Product::create($product);

            if ($shop_id) {
                $this->o2oGoodsProductsRepository->create([
                    'goods_id' => $goods->id,
                    'o2o_goods_id' => $o2oGoodsId,
                    'shop_id' => $shop_id,
                    'product_id' => $bproduct->id,
                    'store_nums' => 0,
                ]);
            }
        }

        foreach ($colors as $cl) {
            $specValue = SpecsValue::where('name', $cl)->first();
            if (!GoodsSpecRelation::where('goods_id', $goods->id)->where('spec_value_id', $specValue->id)->first()) {
                GoodsSpecRelation::create([
                    'goods_id' => $goods->id,
                    'spec_id' => 2,
                    'spec_value_id' => $specValue->id,
                    'alias' => $cl
                ]);
            }


        }

        foreach ($sizes as $sz) {
            $specValue = SpecsValue::where('name', $sz)->first();
            if (!GoodsSpecRelation::where('goods_id', $goods->id)->where('spec_value_id', $specValue->id)->first()) {
                GoodsSpecRelation::create([
                    'goods_id' => $goods->id,
                    'spec_id' => 1,
                    'spec_value_id' => $specValue->id,
                    'alias' => $sz
                ]);
            }

        }
    }

    /**
     * 处理分类
     * @param $_category
     * @return array|bool
     */
    private function importCategory($_category, $goods_no)
    {
        $ids = [];
        if (!$cate = Category::where('name', $_category)->first()) {
            $cate = Category::create(['name' => $_category]);
        }
        return $ids[] = $cate->id;
    }

    private function combineArray($arr1, $arr2)
    {
        $result = [];
        foreach ($arr1 as $item1) {
            $color = SpecsValue::where('name', $item1)->first();
            foreach ($arr2 as $item2) {
                $size = SpecsValue::where('name', $item2)->first();
                $temp = [];
                $temp[] = $color->id;
                $temp[] = $size->id;
                $result[] = $temp;
            }
        }

        $a = array_map(function ($item) {
            sort($item);
            return $item;
        }, $result);

        return $a;
    }

    private function combineArraySr($arr1, $arr2, $goods)
    {
        $result = [];
        $sku = [];
        foreach ($arr1 as $item1) {
            $color = SpecsValue::where('name', $item1)->first();
            $colorSku = $this->colorCode($item1);

            foreach ($arr2 as $item2) {
                $size = SpecsValue::where('name', $item2)->first();

                if (str_contains($goods->name, ['鞋', '鞋子'])) {
                    $sizeSku = $item2;
                } else {
                    $sizeSku = $this->sizeCode($goods->style_id, $item2);
                }

                $temp = [];
                $temp[] = $color->id;
                $temp[] = $size->id;
                $result[] = $temp;
                $sku[] = $goods->goods_no . $colorSku . $sizeSku;
            }
        }

        $a = array_map(function ($item) {
            sort($item);
            return $item;
        }, $result);

        return [$a, $sku];
    }

    private function colorCode($color)
    {
        $colorArr = [
            'A06' => '米白',
            'A07' => '黑色',
            'A16' => '黑白条',
            'B01' => '红色',
            'B02' => '橘红',
            'B07' => '锈红',
            'B10' => '桔色',
            'B11' => '粉色',
            'B15' => '藕粉',
            'B16' => '皮粉',
            'B18' => '橙色',
            'B19' => '砖红',
            'C01' => '黄色',
            'C08' => '米黄',
            'D01' => '蓝色',
            'D02' => '浅蓝',
            'D03' => '深蓝',
            'D04' => '宝蓝',
            'E01' => '灰色',
            'E02' => '花灰',
            'F01' => '绿色',
            'F04' => '浅绿',
            'F06' => '灰绿',
            'F07' => '军绿',
            'F09' => '墨绿',
            'G01' => '紫色',
            'H01' => '杏色',
            'H02' => '米杏',
            'H07' => '浅杏',
            'I01' => '棕色',
            'I04' => '驼色',
            'I06' => '卡其色',
            'I07' => '咖色',
            'I08' => '深咖',
            'I09' => '浅咖',
            'I12' => '浅卡其',
            'E07' => '灰紫',
            'E03' => '深灰',
            'D08' => '蓝绿'

        ];

        $colorCode = array_search($color, $colorArr);
        if (!$colorCode) {
            return 'AAA';
        }
        return $colorCode;

    }

    private function sizeCode($style, $size)
    {
        if ($style == 1) {
            $sizeArr = [
                '05' => '100',
                '07' => '110',
                '09' => '120',
                '11' => '130',
                '13' => '140'
            ];
        } else {
            $sizeArr = [
                'XS' => '80',
                '0S' => '90',
                '0M' => '100',
                '0L' => '110',
                'XL' => '120'
            ];
        }

        $sizeCode = array_search($size, $sizeArr);
        if (!$sizeCode) {
            return $size;
        }
        return $sizeCode;
    }


}